package com.cooba.game_fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cooba.R;
import com.cooba.activitys.GameDetailsActivity;
import com.cooba.adapter.GameAdapter;
import com.cooba.application.MyApplication;
import com.cooba.bean.BannerBean;
import com.cooba.bean.GameBean;
import com.cooba.content_frament.BaseFragment;
import com.cooba.pullTorefresh.PullToRefreshBase;
import com.cooba.pullTorefresh.PullToRefreshListView;
import com.cooba.utils.ACache;
import com.cooba.utils.CarURL;
import com.cooba.utils.CommonUtil;
import com.cooba.utils.Constants;
import com.cooba.utils.ServerURL;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2015/12/29.
 * 战争游戏
 */
public class GameWarFrament extends BaseFragment {
    private View view;
    private PullToRefreshListView rListView;
    private boolean isIncar;
    private boolean first_flag = true;
    private BannerBean banner;
    private HttpUtils httpUtils;
    private RequestParams params;
    private String mac;
    private ACache acache;
    private GameAdapter mAdapter;
    private String next_key = "0";
    private GameBean gamebean;
    private int currentpage = 0;

    private List<GameBean.GameInfo> gameInfoList=new ArrayList<>();
    private boolean mIsFirstLoad=true;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        try {
            if (view == null) {
                view = initview(inflater);
            }
            return view;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private View initview(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.game_recommend_fragment, null, false);
        initPullTorefresh(view);
        initLoadViewHelper(rListView);
        acache = ACache.get(getContext());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION_UPDATE_DOWNLOAD_PROGRESS);
        getContext().registerReceiver(myReceiver, intentFilter);
        return view;
    }

    private void initPullTorefresh(View view) {
        rListView = (PullToRefreshListView) view.findViewById(R.id.lv_game);
        if (isIncar) {
            rListView.setPullRefreshEnabled(false);
        } else {
            rListView.setPullRefreshEnabled(true);
        }
        //rListView.setPullRefreshEnabled(true);
        rListView.setPullLoadEnabled(true);  //上拉加载，屏蔽
        rListView.setScrollLoadEnabled(true); //设置滚动加载可用
        rListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {//下拉刷新
                if (first_flag) {
                    getFirstData();
                } else {
                    getRefreshData();
                }
                String stringDate = CommonUtil.getStringDate();
                rListView.setLastUpdatedLabel(stringDate);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {//上拉加载
                getMoreData();
            }
        });

        rListView.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String gameid;
                if (banner != null && banner.getBannerList() != null && banner.getBannerList().size() > 0) {
                    gameid = mAdapter.getList().get(position - 1).getId();
                } else {
                    gameid = mAdapter.getList().get(position).getId();
                }
                Intent intent = new Intent(getActivity(), GameDetailsActivity.class);
                intent.putExtra("game_id", gameid);
                intent.putExtra("dir_name", "war_game");
                startActivity(intent);
            }
        });

    }


    //获取顶部广告条
    private void getBanner() {
        String urlbanner;
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final String now_time = sDateFormat.format(new java.util.Date());
        httpUtils = new HttpUtils();
        params = new RequestParams();
        params.addBodyParameter("now_time", now_time);
        params.addBodyParameter("tag", "war_game");
        if (isIncar) {
            params.addBodyParameter("mac", mac);
            urlbanner = CarURL.bannerList;
        } else {
            urlbanner = ServerURL.httpUrl + ServerURL.bannerList;
        }
        httpUtils.send(HttpRequest.HttpMethod.POST, urlbanner, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "游戏广告获取失败");
                String cacheData = acache.getAsString("war_game_banner");
                if (cacheData != null) {
                    banner = new Gson().fromJson(cacheData, BannerBean.class);
                    if (banner.getBannerList() != null && banner.getBannerList().size() > 0) {
                        initHeadView();
                    }
                } else {
                    getFirstData();
                }
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "游戏广告获取成功" + responseInfo.result);
                try {
                    banner = new Gson().fromJson(responseInfo.result, BannerBean.class);
                    if (banner.getBannerList() != null && banner.getBannerList().size() > 0) {
                        initHeadView();
                        acache.put("war_game_banner", responseInfo.result, SAVE_TIME);
                    } else {
                        getFirstData();
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getFirstData() {
        if (mIsFirstLoad){
            helper.showLoading("正在加载...");
        }
        String urlgamelist;
        httpUtils = new HttpUtils();
        params = new RequestParams();
        params.addBodyParameter("dir_name", "war_game");
        params.addBodyParameter("next_key", next_key);
        params.addBodyParameter("page_size", "10");
        if (isIncar) {
            urlgamelist =CarURL.gameRecommendList;
        } else {
            urlgamelist = ServerURL.httpUrl + ServerURL.gameRecommendList;
        }
        httpUtils.send(HttpRequest.HttpMethod.POST, urlgamelist, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取游戏失败");
                String cacheData = acache.getAsString("war_game_first");//从缓存中取数据
                Log.d("wei--", "读取:" + acache.getAsString("war_game_first"));
                if (cacheData != null) {
                    first_flag = false;
                    gamebean = new Gson().fromJson(cacheData, GameBean.class);
                    if (mAdapter == null) {
                        mAdapter = new GameAdapter(getActivity(), gamebean.getGameList());
                        rListView.getRefreshableView().setAdapter(mAdapter);
                    } else {
                        mAdapter.setList(gamebean.getGameList());
                    }
                    if (gamebean.getNext_key() == null) {
                        next_key = String.valueOf(gamebean.getGameList().size() + Integer.parseInt(next_key));
                    } else {
                        next_key = gamebean.getNext_key();
                    }
                    if (gamebean.getGameList().size()<10) {
                        rListView.setHasMoreData(false);
                    }
                } else {
                    Toast.makeText(getContext(), "无网络!", Toast.LENGTH_SHORT).show();
                }
                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取游戏成功" + responseInfo.result);
                try {
                    gamebean = new Gson().fromJson(responseInfo.result, GameBean.class);
                    if (gamebean.getGameList()!=null&&gamebean.getGameList().size()>0) {
                        if (mAdapter == null) {
                            mAdapter = new GameAdapter(getActivity(), gamebean.getGameList());
                            rListView.getRefreshableView().setAdapter(mAdapter);
                        } else {
                            mAdapter.setList(gamebean.getGameList());
                        }
                        if (gamebean.getNext_key() == null) {
                            next_key = String.valueOf(gamebean.getGameList().size() + Integer.parseInt(next_key));
                        } else {
                            next_key = gamebean.getNext_key();
                        }
                        gameInfoList.addAll(gamebean.getGameList());
                        acache.put("war_game_first", responseInfo.result, SAVE_TIME);//将数据存入缓存中，有效时间设置为1个月
                        first_flag = false;
                        if (gamebean.getGameList().size()<10) {
                            rListView.setHasMoreData(false);
                        }
                        mIsFirstLoad = false;
                        helper.restore();
                    }else {
                        helper.showEmpty("暂时没有数据", "重新加载", true,new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                helper.restore();
                                getRefreshData();
                            }
                        });
                        //Toast.makeText(getContext(), "暂时没有新数据啦", Toast.LENGTH_SHORT).show();
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }
        });
    }

    private void getRefreshData() {
        next_key="0";
        httpUtils = new HttpUtils();
        params = new RequestParams();
        params.addBodyParameter("dir_name", "war_game");
        params.addBodyParameter("next_key", next_key);
        params.addBodyParameter("page_size", "10");
        String urlgamelist;
        if (isIncar) {
            urlgamelist = CarURL.gameRecommendList;
        } else {
            urlgamelist = ServerURL.httpUrl + ServerURL.gameRecommendList;
        }

        httpUtils.send(HttpRequest.HttpMethod.POST, urlgamelist, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取游戏失败");
                String cacheData = acache.getAsString("war_game_refresh_" + next_key);//从缓存中取数据
                if (cacheData != null) {
                    gamebean = new Gson().fromJson(cacheData, GameBean.class);
                    if (gamebean.getGameList() != null&&gamebean.getGameList().size()>0) {
                        mAdapter.addNewData(gamebean.getGameList());
                        if (gamebean.getNext_key() == null) {
                            next_key = String.valueOf(gamebean.getGameList().size() + Integer.parseInt(next_key));
                        } else {
                            next_key = gamebean.getNext_key();
                        }
                        if (gamebean.getGameList().size()<10) {
                            rListView.setHasMoreData(false);
                        }
                    }
                } else {
                    Toast.makeText(getContext(), "无网络!", Toast.LENGTH_SHORT).show();
                }
                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取游戏成功" + responseInfo.result);
                try {
                    gamebean = new Gson().fromJson(responseInfo.result, GameBean.class);
                    if (gamebean.getGameList() != null&&gamebean.getGameList().size()>0) {
                        // mAdapter.addNewData(gamebean.getGameList());
                        mAdapter.setList(gamebean.getGameList());
                        if (gamebean.getNext_key() == null) {
                            next_key = String.valueOf(gamebean.getGameList().size() + Integer.parseInt(next_key));
                        } else {
                            next_key = gamebean.getNext_key();
                        }
                        acache.put("war_game_refresh_" + next_key, responseInfo.result, SAVE_TIME);//将数据存入缓存中，有效时间设置为1个月
                        if (gamebean.getGameList().size()<10) {
                            rListView.setHasMoreData(false);
                        }
                    } else {
                        helper.showEmpty("暂时没有数据", "重新加载", true,new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                helper.restore();
                                getRefreshData();
                            }
                        });
                        //Toast.makeText(getContext(), "暂时没有新数据啦", Toast.LENGTH_SHORT).show();
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }
        });
    }


    private void getMoreData() {
        httpUtils = new HttpUtils();
        params = new RequestParams();
        Log.d("wei", "next_key" + next_key);
        params.addBodyParameter("dir_name", "war_game");
        params.addBodyParameter("next_key", next_key);
        params.addBodyParameter("page_size", "10");
        String urlgamelist;
        if (isIncar) {
            urlgamelist = CarURL.gameRecommendList;
        } else {
            urlgamelist = ServerURL.httpUrl + ServerURL.gameRecommendList;
        }
        httpUtils.send(HttpRequest.HttpMethod.POST, urlgamelist, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取游戏失败");
                currentpage++;
                String cacheData = acache.getAsString("war_game_load_more_" + currentpage);//从缓存中取数据
                Log.d("wei--", "加载游戏更多读取:" + acache.getAsString("war_game_load_more_" + currentpage));
                if (cacheData != null) {
                    gamebean = new Gson().fromJson(cacheData, GameBean.class);
                    if (gamebean.getGameList() != null&&gamebean.getGameList().size()>0) {
                        mAdapter.addMoreData(gamebean.getGameList());
                        if (gamebean.getNext_key() == null) {
                            next_key = String.valueOf(gamebean.getGameList().size() + Integer.parseInt(next_key));
                        } else {
                            next_key = gamebean.getNext_key();
                        }
                        if (gamebean.getGameList().size()<10) {
                            rListView.setHasMoreData(false);
                        }
                    } else {
                        Toast.makeText(getContext(), "没有更多数据啦", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    currentpage--;
                    Toast.makeText(getContext(), "无网络!", Toast.LENGTH_SHORT).show();
                }
                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取成功" + responseInfo.result);
                try {
                    gamebean = new Gson().fromJson(responseInfo.result, GameBean.class);
                    if (gamebean.getGameList() != null && gamebean.getGameList().size() > 0) {
                        mAdapter.addMoreData(gamebean.getGameList());
                        if (gamebean.getNext_key() == null) {
                            next_key = String.valueOf(gamebean.getGameList().size() + Integer.parseInt(next_key));
                        } else {
                            next_key = gamebean.getNext_key();
                        }
                        currentpage++;
                        acache.put("war_game_load_more_" + currentpage, responseInfo.result, SAVE_TIME);//将数据存入缓存中，有效时间设置为1个月
                        gameInfoList.addAll(gamebean.getGameList());
                        if (gamebean.getGameList().size()<10) {
                            rListView.setHasMoreData(false);
                        }
                    } else {
                        Toast.makeText(getContext(), "没有更多数据啦", Toast.LENGTH_SHORT).show();
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }

                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }
        });
    }

    private void initHeadView() {
        //rListView.getRefreshableView().setAdapter(null);
        rListView.getRefreshableView().addHeaderView(getCustomHeaderView(getContext(), banner.getBannerList()));
        getFirstData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            Log.d("wei--", "war_game:" + isVisibleToUser);
            initIncar();
            if (banner == null) {
                getBanner();
            }
        }
    }

    public void initIncar() {
        MyApplication application = MyApplication.getMyApplication();
        isIncar = application.getIsInCar();
        mac = application.getMac();
    }


    private BroadcastReceiver myReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent intent) {
            // TODO Auto-generated method stub
            if (intent.getAction().equals(Constants.ACTION_UPDATE_DOWNLOAD_PROGRESS)) {
                GameBean.GameInfo gameInfo = (GameBean.GameInfo) intent.getSerializableExtra("download_data");
                updateView(gameInfo);
            }

        }

    };

    private void updateView(GameBean.GameInfo gameInfo) {

        if (gameInfo==null)return;
        int itemIndex=0;
        Boolean flag=false;
        for (GameBean.GameInfo gameinfo: gameInfoList){
            if (gameInfo.getId().equals(gameinfo.getId())){
                if (banner != null && banner.getBannerList() != null && banner.getBannerList().size() > 0) {
                    itemIndex = gameInfoList.indexOf(gameinfo)+1;
                    flag=true;
                }else {
                    itemIndex = gameInfoList.indexOf(gameinfo);
                    flag=false;
                }
                Log.d("wei","位置:"+itemIndex);
                updateView1(itemIndex,flag);
                break;
            }
        }

    }

    private void updateView1(int itemIndex,boolean flag) {
        //得到第一个可显示控件的位置，
        int visiblePosition = rListView.getRefreshableView().getFirstVisiblePosition();
        //只有当要更新的view在可见的位置时才更新，不可见时，跳过不更新
        if (itemIndex - visiblePosition >= 0) {
            //得到要更新的item的view
            View view = rListView.getRefreshableView().getChildAt(itemIndex - visiblePosition);

            //调用adapter更新界面
            mAdapter.updateView(view, itemIndex,flag);
        }
    }
}